package com.zhkjnet.zhyy.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class HttpUtil {

    //private final static OkHttpClient client = new OkHttpClient();
    private final static OkHttpClient client1 = new OkHttpClient.Builder()
            .connectTimeout(60000, TimeUnit.MILLISECONDS)
            .readTimeout(60000, TimeUnit.MILLISECONDS)
            .build();

    private final static MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private final static ObjectMapper objectMapper = new ObjectMapper();

    private final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

    public static String post(String url, String json) throws IOException {
        logger.debug("http post url : " + url + ", json : " + json);
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client1.newCall(request).execute();
        return response.body().string();
    }

    public static String post(String url, Object obj) throws IOException {
        return post(url, objectMapper.writeValueAsString(obj));
    }
   /* public String HttpPost(String param1,String param2,String url) throws Exception{
        Map<String,String> personMap = new HashMap<String,String>();
        personMap.put("param1",param1);
        personMap.put("param1",param2);
        List<NameValuePair> list = new LinkedList<NameValuePair>();
        for(Entry<String,String> entry:personMap.entrySet()){
            list.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
        }
        HttpPost httpPost = new HttpPost(url);
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list,"utf-8");
        httpPost.setEntity(formEntity);
        HttpClient httpCient = HttpClients.CreatDefault();
        HttpResponse httpresponse = null;
        try{
        httpresponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpresponse.getEntity();
        String response = EntityUtils.toString(httpEntity, "utf-8");
        return response;
        }catch(ClientProtocolException e){
                System.out.println("http请求失败，uri{},exception{}");
            }catch(IOException e){
                System.out.println("http请求失败，uri{},exception{}");
            }
            return null;
    }*/

}
